package com.wowangz.cms.topic.poster.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.wowangz.cms.common.mongo.MongoDBManager;
import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.FileTools;
import com.wowangz.cms.common.utils.MessageObject;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.common.utils.SysConstant.NewsBusinessstatus;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.exception.ServiceException;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.topic.poster.entity.PosterEntity;
import com.wowangz.cms.topic.poster.service.PosterService;

@Controller
@Scope("prototype")
public class PosterController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(PosterController.class);
	private MessageObject message = new MessageObject();
	private String tempFolder = "";

	/**
	 * @描述： 删除海报
	 * 
	 * @author HUANGYUAN
	 * @TIME:2015年9月22日 下午2:14:11
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "/topic/poster/deletePoster.json", method = { RequestMethod.GET })
	public void deletePoster(HttpServletResponse response, HttpServletRequest request) {
		try {
			PosterService posterService = (PosterService) IssTransactionContainer.getInstance(PosterService.class, false);
			String id = request.getParameter("id");
			if (StringUtils.isNotEmpty(id)) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", id);
				PosterEntity poster = posterService.findOnePosterByMap(map);
				if (poster != null) {
					poster.setStatusid(SysConstant.RecordStatus.INVALID);
					posterService.deletePoster(poster);
					getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
				}
			} else {
				getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
			}
		} catch (ServiceException e) {
			logger.info("删除海报出错", e.getMessage());
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
			e.printStackTrace();
		} finally {
			try {
				AjaxDataEntity entity = new AjaxDataEntity();
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "/topic/poster/upload.web", method = { RequestMethod.POST, RequestMethod.GET })
	public void upload(MultipartHttpServletRequest request, HttpServletResponse response) {
		try {
			MongoDBManager manager = MongoDBManager.getDefaultMongoDBManager();
			Long attachmentSize = manager.getPictureSize();
			Iterator<String> iterator = request.getFileNames();
			PosterService posterService = (PosterService) IssTransactionContainer.getInstance(PosterService.class, true);
			while (iterator.hasNext()) {
				MultipartFile multipartFile = request.getFile(iterator.next());
				String contentType = multipartFile.getContentType();
				String name = multipartFile.getOriginalFilename();
				float size = multipartFile.getSize() / (1024);
				Long filesize = Long.valueOf(attachmentSize) / 1024;
				String suffix = FileTools.getFileExtension(name);
				String attSize = "";
				if (size < filesize) {
					if (size >= 1024 && size < 1024 * 1024) {
						attSize = (size / 1024) + "MB";
					} else if (filesize >= 1024 * 1024) {
						attSize = (size / 1024 / 1024) + "GB";
					} else if (size < 1) {
						attSize = size + "B";
					} else {
						attSize = size + "KB";
					}
					String mongofilename = ServletUtils.uploadMongodbfile(multipartFile.getInputStream(), manager, manager.getPictureDBName());
					
					Long checkstatus = SysConstant.CheckStatus.SAVE;
					PosterEntity poster = new PosterEntity(checkstatus, SysConstant.CheckStatus.getName(checkstatus), name, attSize,
							mongofilename, suffix, contentType);
//					if (StringUtils.isNotEmpty(sortnumber)) {
					poster.setSortnumber(1l);
//					}
					poster.setStatus(SysConstant.CommonUsedStatus.STOP);
					poster.setInputuserid(getUserContext().getLoginUser().getId());
					poster.setInputtime(new Date());
					poster.setModifytime(new Date());
					poster.setModifyuserid(getUserContext().getLoginUser().getId());
					poster.setStatusid(SysConstant.RecordStatus.VALID);
					posterService.posterSave(poster);
					message.setInforMessage(MessageResourcesUtils.getMessage(request, "topic.poster.uploadfile.success"));
				} else {
					attSize = (filesize) + "KB";
					message.setInforMessage(null);
					message.setErrorMessage(name + MessageResourcesUtils.getMessage(request, "topic.poster.status.alert7") + attSize);
					break;
				}
			}
		} catch (Exception e) {
			logger.debug(e.getMessage());
			e.printStackTrace();
			message.setErrorMessage(MessageResourcesUtils.getMessage(request, "topic.poster.uploadfile.failur"));
		} finally {
			try {
				response.getWriter().write(message.getJsonMapper(message));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	/**
	 * @描述：查找一条记录
	 * @author HUANGYUAN
	 * @TIME:2015年9月24日 下午4:26:30
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/topic/poster/findOnePoster.json")
	public void findOnePoster(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		MongoDBManager manager = MongoDBManager.getDefaultMongoDBManager();
		PosterService posterService = (PosterService) IssTransactionContainer.getInstance(PosterService.class, false);
		try {
			if (StringUtils.isNotEmpty(id)) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", id);
				map.put("statusid", SysConstant.RecordStatus.VALID);
				PosterEntity poster = posterService.findOnePosterByMap(map);
				if (poster != null) {
					poster.setPictureUrl(manager.getAccessUrl());
					message.setObject(poster);
					message.setInforMessage(MessageResourcesUtils.getMessage(request, "topic.poster.select.success"));
				} else {
					message.setErrorMessage(MessageResourcesUtils.getMessage(request, "topic.poster.select.failur"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			message.setErrorMessage(MessageResourcesUtils.getMessage(request, "topic.poster.select.failur"));
		} finally {
			try {
				response.getWriter().write(message.getJsonMapper(message));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private DataResult getDataResult(HttpServletRequest request, PangingParam pangingParam, Map<String, Object> paramMap) throws Exception {
		paramMap.put("statusid", SysConstant.RecordStatus.VALID);
		PosterService posterService = (PosterService) IssTransactionContainer.getInstance(PosterService.class, false);
		long resultCount = posterService.findPosterCountByMap(paramMap);
		List<PosterEntity> news = posterService.findPosterPageByMap(paramMap);
		DataStyle dataStyle = new DataStyle();
		dataStyle.setPageIndex(pangingParam.getPage());
		dataStyle.setDataCount(resultCount);
		dataStyle.setDataList(news);
		dataStyle.addDepict("filename", DataTypeConstant.STRING);// 文件名称
		dataStyle.addDepict("filesize", DataTypeConstant.STRING);// 文件大小
		dataStyle.addDepict("mongofilename", DataTypeConstant.STRING);// 文件别名
		dataStyle.addDepict("sortnumber", DataTypeConstant.LONG);// 排序编号
		dataStyle.addDepict("suffix", DataTypeConstant.STRING);// 文件后缀
		dataStyle.addDepict("type", DataTypeConstant.STRING);// 文件类型
		dataStyle.addDepict("status", DataTypeConstant.LONG);// 启用状态
		dataStyle.addDepictByFunction("statusname", SysConstant.CommonUsedStatus.class, "getName", new Class[] { long.class });// 发布状态
		dataStyle.addDepictByFunction("statusid", SysConstant.RecordStatus.class, "getName", new Class[] { long.class });// 状态
		dataStyle.addDepict("id", DataTypeConstant.LONG);
		DataResult dataResult = PangingTools.buildResultPagerInfo(dataStyle);
		return dataResult;
	}

	/**
	 * @描述：获得海报的数据
	 * @author HUANGYUAN
	 * @TIME:2015年9月22日 下午4:25:01
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/topic/poster/getPosterJson.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void getPosterJson(HttpServletRequest request, HttpServletResponse response) {
		try {
			PangingParam pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			Map<String, Object> map = com.wowangz.cms.syscore.utils.ServletUtils.getParametersToHashMap(request);
			DataGrid dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			if (StringUtils.isNotEmpty(request.getParameter("parentcolumn"))) {
				map.put("columnid", request.getParameter("parentcolumn"));
			}
			map.put("businessstatus", NewsBusinessstatus.DRAFT);
			DataResult dataResult = getDataResult(request, pangingParam, map);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, getUserContext()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @描述：停用或者启用海报
	 * @author HUANGYUAN
	 * @TIME:2015年9月24日 下午3:34:00
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/topic/poster/startOrStopPoster.json", method = RequestMethod.GET)
	public void startOrStopPoster(HttpServletRequest request, HttpServletResponse response) {
		PosterService posterService = (PosterService) IssTransactionContainer.getInstance(PosterService.class, false);
		AjaxDataEntity entity = new AjaxDataEntity();
		String idStrings = request.getParameter("ids");
		String status = request.getParameter("status");
		try {
			if (StringUtils.isNotEmpty(idStrings)) {
				String[] strings = idStrings.split(",");
				for (int i = 0; i < strings.length; i++) {
					String id = strings[i];
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", id);
					PosterEntity poster = posterService.findOnePosterByMap(map);
					if (entity != null) {
						poster.setStatus(Long.valueOf(status));
						posterService = (PosterService) IssTransactionContainer.getInstance(PosterService.class, true);
						posterService.updatePoster(poster);
						String success = MessageResourcesUtils.getMessage(request, "topic.poster.status.alert1");
						if (Long.valueOf(status) == SysConstant.CommonUsedStatus.STOP) {
							success = MessageResourcesUtils.getMessage(request, "topic.poster.status.alert3");
						}
						getUserContext().setInfoMessage(success);
					} else {
						String error = MessageResourcesUtils.getMessage(request, "topic.poster.status.alert2");
						getUserContext().setErrorMessage(error);
						break;
					}
				}
			}
		} catch (ServiceException e) {
			String error = MessageResourcesUtils.getMessage(request, "topic.poster.status.alert2");
			if (Long.valueOf(status) == SysConstant.CommonUsedStatus.START) {
				error = MessageResourcesUtils.getMessage(request, "topic.poster.status.alert4");
			}
			getUserContext().setErrorMessage(error);
			e.printStackTrace();
		} catch (NumberFormatException e) {
			String error = MessageResourcesUtils.getMessage(request, "topic.poster.status.alert3");
			if (Long.valueOf(status) == SysConstant.CommonUsedStatus.START) {
				error = MessageResourcesUtils.getMessage(request, "topic.poster.status.alert4");
			}
			getUserContext().setErrorMessage(error);
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @描述：进入上传海报的页面
	 * @author HUANGYUAN
	 * @TIME:2015年9月22日 下午4:25:39
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/topic/poster/toPosterAdd.web")
	public String toPosterAdd(Model model) {
		MongoDBManager manager = MongoDBManager.getDefaultMongoDBManager();
		model.addAttribute("attachmentSize", manager.getPictureSize());
		PosterService posterService = (PosterService) IssTransactionContainer.getInstance(PosterService.class, false);
		model.addAttribute("sortnumber", posterService.findMaxSortnumber());
		return "/WEB-INF/jsp/topic/poster/posterAdd";
	}

	/**
	 * @描述:获得修改页面的信息
	 * @author HUANGYUAN
	 * @TIME:2015年9月24日 下午4:47:53
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/topic/poster/toPosterEdit.web")
	public String toPosterEdit(HttpServletRequest request, Model model) {
		String id = request.getParameter("id");
		PosterService posterService = (PosterService) IssTransactionContainer.getInstance(PosterService.class, false);
		PosterEntity poster = new PosterEntity();
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", id);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			poster = posterService.findOnePosterByMap(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("poster", poster);
		return "/WEB-INF/jsp/topic/poster/posterUpdate";
	}

	/**
	 * @描述：获得海报的列表
	 * @author HUANGYUAN
	 * @TIME:2015年9月22日 下午4:24:46
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/topic/poster/queryPosterList.web", method = { RequestMethod.GET })
	public String queryPosterList(HttpServletRequest request, Model model) {

		return "/WEB-INF/jsp/topic/poster/posterList";
	}

	@RequestMapping(value = "/topic/poster/updatePoster.json", method = RequestMethod.POST)
	public void updatePoster(HttpServletRequest request, HttpServletResponse response, PosterEntity poster) {
		String id = request.getParameter("id");
		AjaxDataEntity entity = new AjaxDataEntity();
		PosterService posterService = (PosterService) IssTransactionContainer.getInstance(PosterService.class, false);
		try {
			poster.setId(Long.valueOf(id));
			posterService.updatePoster(poster);
			getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert6"));
		} catch (ServiceException e) {
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert7"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().write(JSONFactory.toJSONString(entity, getUserContext()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
